import React, { useEffect, useRef, useState } from "react";
import { Table, Row, Col, Input, Form, Button, DatePicker, Space, Divider, Image, message, Modal, Select, QRCode } from 'antd'
import Prefix from '../../components/prefix'
import { SearchOutlined, ExportOutlined } from '@ant-design/icons';
import * as apis from '../../lib/api'
import http from '../../lib/http'
import _, { cloneDeep } from 'lodash'
import moment from 'moment'
import { useNavigate } from "react-router-dom";
import ZH from 'antd/locale/zh_CN'

const { RangePicker } = DatePicker


const Index = () => {
    const [search, setSearch] = useState({page: 1,page_size: 20})
    const [loading, setLoading] = useState(false)
    const [data, setData] = useState()
    const [seleckeys, setSeleckeys] = useState([])
    const [category, setCategory] = useState([])
    const n = useNavigate()


    const loadData = async (s) => {
        try {
            const data = await http.post(apis.ORDER_LIST,s)
            for(let i=0;i<data?.list?.length;i++){
                if(data.list[i].materials){
                    data.list[i].materials = JSON.parse(data.list[i].materials)
                }
                if(data.list[i].printing_code){
                    data.list[i].printing_code = JSON.parse(data.list[i].printing_code)
                }
                
            }
            setData(data)
        } catch (error) {
            
        }
    }

    const onSearch = async (values) => {
        let cpSearch = {...search}
        cpSearch.name = values?.name
        cpSearch.page = 1
        if(values.times && values.times.length === 2){
            cpSearch.start_time = values.times[0].format("YYYY-MM-DD HH:mm:ss")
            cpSearch.end_time = values.times[1].format("YYYY-MM-DD HH:mm:ss")
        }else{
            delete cpSearch.start_time
            delete cpSearch.end_time
        }
        
        if(values.order_nos){
            cpSearch.order_nos = values.order_nos.split(",")
        }else{
            delete cpSearch.order_nos
        }
        setLoading(true)
        await loadData(cpSearch)
        setLoading(false)
        setSearch(cpSearch)
    }

    const pageSearch = async (page,page_size) => {
        let cpSearch = {...search}
        cpSearch.page_size = page_size
        cpSearch.page = page
        setLoading(true)
        await loadData(cpSearch)
        setLoading(false)
        setSearch(cpSearch)
    }

    //创建导出任务
    const createExportTask = async () => {
        setLoading(true)
        try {
            await http.post(apis.ORDER_DOWNLOAD_TASK_CREATE,{
                order_nos: seleckeys
            })
            message.success("操作成功")
            n("/export/list")
        } catch (error) {
            
        }
        setLoading(false)
    }

    useEffect(()=>{
        setLoading(true)
        loadData(search).then(r => {
            setLoading(false)
        })
        // eslint-disable-next-line
    },[])

    const columns = [
        {
            title: '订单号',
            dataIndex: 'order_no',
            key: 'order_no'
        },
        {
            title: '名字',
            dataIndex: 'name',
            key: 'name'
        },
        {
            title: '封面',
            dataIndex: 'cover',
            key: 'cover',
            render: (v) => (
                <Image width={80} height={80} src={process.env.REACT_APP_OSS_URL+v} fallback="" />
            )
        },
        {
            title: '颜色',
            dataIndex: 'color',
            key: 'color',
            render: (v,r) => {
                const a = r?.materials?.map_info?.find(i => i.color === v)
                if(a){
                    return <div style={{
                        display: "flex",
                        alignItems: "center"
                    }}>
                        <span style={{
                            display: "inline-block",
                            width: 16,
                            height: 16,
                            background: v,
                            marginRight: 6
                        }}></span>
                        <span>{a.name}</span>
                    </div>
                }
            }
        },
        {
            title: '价格明细',
            dataIndex: 'price',
            key: 'price',
            render: (j,r) => {
                let cutArr = []
                let basePrice = parseFloat((r.product_price/100).toFixed(2))
                if (r?.printing_code) {
                    for (let i = 0; i < r?.printing_code?.length; i++) {
                        let code = r?.printing_code[i]
                        let f = r?.materials?.cutparts?.find((v) => v.code === code)
                        if (f) {
                            basePrice += f.price
                            cutArr.push(f)
                        }
                    }
                }
                return <div>
                    <div>基础价格：¥ {(r.product_price/100).toFixed(2)}</div>
                    {
                        cutArr?.map(i => (
                            <div key={i.code}>{i.txt}印刷：¥ {i.price.toFixed(2)}</div>
                        ))
                    }
                    <div style={{color: "red"}}>合计：¥ {basePrice.toFixed(2)}</div>
                </div>
            }
        },
        {
            title: '创建时间',
            dataIndex: 'created_at',
            key: 'created_at',
            render: (v) => (
                <span>{moment(v).format("YYYY-MM-DD HH:mm:ss")}</span>
            )
        },
        {
            title: '操作',
            dataIndex: 'a',
            key: 'a',
            render: (v,r) => (
                <Space>
                    <Button type="link" style={{padding: 0}} onClick={() => {
                        Modal.confirm({
                            icon: <></>,
                            content: <div>
                                <iframe src={`${r.h5_host ? r.h5_host:process.env.REACT_APP_H5_URL}/preview/${r.resource_url}`} style={{
                                    border: "none",
                                    display: "block",
                                    width: 375,
                                    height: 667
                                }}></iframe>
                            </div>
                        })
                    }}>查看设计</Button>
                    <Button type="link" style={{padding: 0}} onClick={()=>{
                        Modal.confirm({
                            content: <QRCode size={370} value={`${r.h5_host ? r.h5_host:process.env.REACT_APP_H5_URL}/preview/${r.resource_url}`} />,
                            icon: <></>
                        })
                    }}>二维码</Button>
                </Space>
            )
        }
    ]

    return (
        <div>
            <Form onFinish={onSearch}>
                <Row gutter={16}>
                    <Col span={8}>
                        <Form.Item name="name">
                            <Prefix label="名称">
                                <Input allowClear placeholder="请输入名称或订单号" />
                            </Prefix>
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item name="times">
                            <Prefix label="下单时间">
                                <RangePicker locale={ZH} showTime />
                            </Prefix>
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item name="order_nos">
                            <Prefix label="订单号">
                                <Input allowClear placeholder="多个使用,隔开" />
                            </Prefix>
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={16}>
                    <Col span={8}>
                        <Form.Item>
                            <Space>
                                <Button loading={loading} type="primary" htmlType="submit" icon={<SearchOutlined />}>查询</Button>
                                <Button loading={loading} disabled={seleckeys.length === 0} onClick={createExportTask} icon={<ExportOutlined />}>一键导出</Button>
                                <span>已选：{seleckeys.length}</span>
                            </Space>
                        </Form.Item>
                    </Col>
                </Row>
            </Form>
            <Table 
                rowKey={'order_no'}
                dataSource={data?.list || []} 
                loading={loading} 
                columns={columns}
                pagination={{
                    showQuickJumper: true,
                    showSizeChanger: true,
                    onChange: pageSearch,
                    total: data?.total,
                    current: data?.page,
                    pageSize: data?.page_size
                }}
                rowSelection={{
                    onChange: (keys) => {
                        let cpseleckeys = [...seleckeys]
                        for(let i=0;i<data?.list.length;i++){
                            let k = data?.list[i]
                            let fi = cpseleckeys.findIndex(j => j === k.order_no)
                            if(fi !== -1){
                                cpseleckeys.splice(fi,1)
                            }
                        }
                        setSeleckeys([...new Set([...cpseleckeys,...keys])])
                    },
                    selectedRowKeys: seleckeys
                }}
                scroll={{
                    y: 'calc(100vh - 475px)'
                }}
            />
        </div>
    )
}

export default Index